# Copyright (c) 2008-2009 Mikhail Chernov 
#
# This file is part of dcExplorer.
#
# dcExplorer is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# dcExplorer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with dcExplorer.  If not, see <http://www.gnu.org/licenses/>.

package dcExplorer::storage::OriginalXML;
use strict;
use loader::OriginalXML;
use core::Empire;
use FileHandle;
use Error;

sub new
{
	my $proto = shift;
	my $class = ref($proto) || $proto;
	my $self = {};
	$self->{Path} = shift;
	throw Error::Simple("Base path expected to exist") unless -e $self->{Path};
	$self->{Id} = shift;
	$self->{Path} .= "/".$self->{Id};
	mkdir $self->{Path} unless -e $self->{Path};
	bless ($self, $class);
	return $self;
}

sub Download
{
	my $self = shift;
	my $session = shift;
	my $types = shift;
#  As per GribUser:
#	all (general, myplanets, buildings, foreign_fleets, diplomacy, requests) 
#	known_planets (в all не входит)
#	designhouse (не работает пока и не факт, что будет – нафиг оно не надо, подозреваю, а если надо, то неочевидно, в каком виде)
	my $empire = dcExplorer::core::Empire->new($self->{Id});
	my $updateBuilder = dcExplorer::loader::OriginalXML->new($empire);
	my %docs;
	for my $type (@{$types})
	{
		$docs{$type} = $session->GetXML($type);
		throw Error::Simple("Unable to get <".$type."> document!") unless defined $docs{$type};
	}
	for my $type (@{$types})
	{
		$updateBuilder->loadXML($docs{$type});
	}
	my $snapshot = $empire->getProp('time_left');
	open FILE, ">>:utf8", $self->{Path}."/snapshots.csv";
	print FILE $empire->getProp('turn').",".$empire->getProp('time_left').",".join(",", @{$types})."\n";
	close FILE;
	mkdir $self->{Path}."/".$empire->getProp('turn') unless (-e $self->{Path}."/".$empire->getProp('turn'));
	mkdir $self->{Path}."/".$empire->getProp('turn')."/".$empire->getProp('time_left');
	for my $type (@{$types})
	{
		open FILE, ">:utf8", $self->{Path}."/".$empire->getProp('turn')."/".$empire->getProp('time_left')."/".$type.".xml";
		print FILE $docs{$type};
		close FILE;
	}
	return $empire;
}

sub GetLast
{
	my $self = shift;
	return dcExplorer::core::Empire->new($self->{Id}) unless (-e $self->{Path}."/snapshots.csv");
	open FILE, "<:utf8", $self->{Path}."/snapshots.csv";
	my $line;
	$line = $_ while <FILE>;
	chomp $line;
	my ($turn, $time, @types) = split /,/, $line;
	return $self->Get($turn, $time, [@types]);
}

sub GetTurn
{
	my $self = shift;
	my $turn = shift;
	return dcExplorer::core::Empire->new($self->{Id}) unless (-e $self->{Path}."/snapshots.csv");
	open FILE, "<:utf8", $self->{Path}."/snapshots.csv";
	my ($time, $types) = (undef, undef);
	while (my $line = <FILE>)
	{
		chomp $line;
		my ($tn, $tm, @ts) = split /,/, $line;
		if ($tn == $turn)
		{
			$time = $tm;
			$types = [@ts];
		}
	}
	return dcExplorer::core::Empire->new($self->{Id}) unless (defined $time);
	return $self->Get($turn, $time, $types);
}

sub GetTurnList
{
	my $self = shift;
	my $list = [];
	return $list unless (-e $self->{Path}."/snapshots.csv");
	open FILE, "<:utf8", $self->{Path}."/snapshots.csv";
	my $turn = 0;
	while (my $line = <FILE>)
	{
		chomp $line;
		my ($tn, $tm, @ts) = split /,/, $line;
		if ($tn != $turn)
		{
			push @{$list}, $turn if ($turn != 0);
			$turn = $tn;
		}
	}
	push @{$list}, $turn if ($turn != 0);
	return $list;
}

sub Get
{
	my $self = shift;
	my $turn = shift;
	my $time = shift;
	my $types = shift;
	my $empire = dcExplorer::core::Empire->new($self->{Id});
	my $updateBuilder = dcExplorer::loader::OriginalXML->new($empire);
	for my $type (@{$types})
	{
		local $/ = undef;
		open FILE, "<:utf8", $self->{Path}."/".$turn."/".$time."/".$type.".xml";
		my $doc = <FILE>;
		close FILE;
		$updateBuilder->loadXML($doc);
	}
	return $empire;
}

1;
